<?php

use think\facade\Db;

/**
 *  生成随机字符串
 */
function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for (
        $i = 0;
        $i < $length;
        $i++
    ) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}


/**
 *  生成手机验证码
 */
function generate_code($length = 6)
{
    $chars = '0123456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $code;
}

// 辅助函数：发送HTTP POST请求
function http_post($url, $params)
{
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($params),
        ),
    );
    $context  = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

function extractListFromData($data)
{

    // 检查是否存在 data 字段
    if (!isset($data['data'])) {
        throw new Exception("JSON 数据中不存在 data 字段");
    }

    // 检查是否存在 list 字段
    if (!isset($data['data']['list'])) {
        throw new Exception("JSON 数据中不存在 list 字段");
    }

    // 返回 list 字段
    return $data['data']['list'];
}

function transLabel($data)
{
    $result = [];
    foreach ($data as $key => $value) {
        $result[] = [
            'label' => $value,
            'value' => $key
        ];
    }
    return $result;
}


/**
 * @describe 判断是否是超级管理员
 * @author: Bobo
 * @date: 2024-12-17 11:59:01 
 * @param [int] @required $userId 用户ID
 * @return bool
 */
function isSuperAdmin(int $userId): bool
{
    if (0 >= $userId) {
        return false;
    }
    $role = Db::table('db_operator')->where('id', $userId)->value('isadmin');
    return $role ==  1;
}
/**
 * 递归获取无限极分类
 * @param array $data 原始数据
 * @return array
 */
function generateTree($items)
{
    $tree = [];
    $itemsByKey = [];

    // 按ID索引所有项（保持原始类型，不强制转换）
    foreach ($items as $item) {
        $itemsByKey[$item['value']] = $item;
        $itemsByKey[$item['value']]['children'] = []; // 初始化children数组
    }

    // 构建树
    foreach ($itemsByKey as $id => $item) {
        if ($item['parent_id'] !== null && isset($itemsByKey[$item['parent_id']])) {
            $itemsByKey[$item['parent_id']]['children'][] = &$itemsByKey[$id];
        } else {
            $tree[] = &$itemsByKey[$id];
        }
    }

    // 解除引用
    unset($item);

    return $tree;
}
